package com.sh.data.engine.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
@Slf4j
public class VarUtil {

    public static String varPattern = "\\$\\{(.+?)\\}";

    public static String systemDate = "system.date";

    public static String getOfflineTaskValue(String var) {

        Pattern pattern = Pattern.compile(varPattern);

        Matcher matcher = pattern.matcher(var);
        if (!matcher.find()) {
            return var;
        } else {
            String key = "@var@";
            String value = matcher.group();
            value = value.replaceFirst("\\$\\{", "");
            value = value.replaceFirst("\\}", "");
            Node node = doParse1(key, value.trim());
            return node.getValue();
        }
    }

    private static Node doParse1(String key, String value) {

        Node node = new Node();
        node.setKey(key);

        // 系统变量
        if (value.trim().startsWith("system.")) {
            String[] vals = value.split(",");
            String val1 = vals[0];
            node.setType(1);
            // 时间变量
            if (val1.contains(systemDate)) {
                String format = "yyyy-MM-dd";
                if (vals.length > 1) {
                    format = vals[1];
                }
                //        String[] val1s = val1.split("-");
                Date date = new Date();
                if (vals.length == 3) {
                    date = DateUtil.getPerDate(date, "d", Integer.parseInt(vals[2].trim()));
                }
                String val2 = DateUtil.formatDate(date, format);

                node.setValue(val2);
            }
        } else {
            node.setType(2);
            node.setValue(value);
        }

        return node;
    }

    @Data
    private static class Node {

        private String key;

        private String value;

        /**
         * type 0-to_db 1-系统 2-自定义
         */
        private int type;
    }

    //    public static void main(String[] args) {
    //      String where = "${system.date,yyyyMMdd,-1}";
    //      where = getWhere(where, null, null, null, null, null, null);
    //      System.out.println(where);
    //    }
}
